package com.example.nettydemo.NIONetty.Http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if(msg instanceof HttpRequest) {
            System.out.println(ctx.pipeline().hashCode());//http每次访问都是新的
            System.out.println("msg类型：" + msg.getClass());
            System.out.println("客户端地址" + ctx.channel().remoteAddress());

            //有的网页获取两次   一次信息  一次获取favicon.ico//logo图标
            //解决方案
            HttpRequest httpRequest = (HttpRequest) msg;

            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("你请求了favicon.ico，不做响应");
                return;
            }
            //回复信息给浏览器  【http协议】
            ByteBuf buf = Unpooled.copiedBuffer("hello,我是服务器", StandardCharsets.UTF_8);

            //构造一个http响应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");//;charset=utf-8 防止乱码
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());

            ctx.writeAndFlush(response);//返回response
        }
    }
}
